package com.fengwk.resource.controller;

import java.net.MalformedURLException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.fengwk.resource.service.FileService;
import com.fengwk.resource.service.PageService;
import com.fengwk.support.exception.BaseException;
import com.fengwk.support.util.CharUtils;
import com.fengwk.support.util.CodeUtils;

import io.swagger.annotations.Api;

@Api(tags = "资源访问控制器")
@Controller
@RequestMapping
public class ResourceController {
	
	public static final String REDIRECT = "redirect:";
	
	@Autowired
	private PageService pageService;
	@Autowired
	private FileService fileService;
	
	@GetMapping("/{name}")
	public String user(@PathVariable("name") String name) throws MalformedURLException {
		String url = pageService.getUrlByName(name);
		return redirect(url);
	}
	
	@RequestMapping
	public String resource(
			@RequestParam(value = "fileId", required = true) Long fileId,
			@RequestParam(value = "thumbnail", required = false) Boolean thumbnail) throws MalformedURLException {
		String url = fileService.getRealUrl(fileId, thumbnail);
		return redirect(url);
	}
	
	private String redirect(String url) {
		if (url == null)
			throw new BaseException("url == null");
		
		StringBuffer sb = new StringBuffer().append(REDIRECT);
		for (int i = 0; i < url.length(); i ++) {
			char c = url.charAt(i);
			if (CharUtils.isChinese(c)) 
				sb.append(CodeUtils.urlEncode(c + ""));
			else
				sb.append(c);
		}
		return sb.toString();
	}

}